package com.wonders.hisdoctor.station.project.vaccine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wonders.his.common.bean.BaseResult;
import com.wonders.his.common.exception.CustomException;
import com.wonders.his.common.utils.StringUtils;
import com.wonders.his.common.utils.validator.ValidateUtils;
import com.wonders.his.common.utils.validator.group.InsertGroup;
import com.wonders.his.framework.dto.LoginUserDTO;
import com.wonders.his.framework.service.TokenService;
import com.wonders.his.framework.utils.oracle.IdUtils;
import com.wonders.hisdoctor.station.constant.Constants;
import com.wonders.hisdoctor.station.constant.ServiceConstant;
import com.wonders.hisdoctor.station.enums.OracleSequenceEnum;
import com.wonders.hisdoctor.station.project.base.domain.PatVaccineInfo;
import com.wonders.hisdoctor.station.project.base.domain.PatVaccineRegister;
import com.wonders.hisdoctor.station.project.base.mapper.PatVaccineInfoMapper;
import com.wonders.hisdoctor.station.project.base.mapper.PatVaccineRegisterMapper;
import com.wonders.hisdoctor.station.project.vaccine.mapper.VaccinationMapper;
import com.wonders.hisdoctor.station.project.vaccine.service.VaccinationService;
import com.wonders.hisdoctor.station.project.vaccine.vo.*;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 张澎_9970
 * @date 2021.6.24 下午 4:38 星期四
 * @desc: 接种登记_实现类
 */
@Service
public class VaccinationServiceImpl implements VaccinationService {
    private IdUtils idUtils;
    private PatVaccineInfoMapper patVaccineInfoMapper;
    private PatVaccineRegisterMapper patVaccineRegisterMapper;
    private VaccinationMapper vaccinationMapper;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
    private TokenService tokenService;

    @Override
    public Integer save(VaccinationVO vaccinationVO, HttpServletRequest request) {
        Integer num = 0;
        Integer infoNum = 0;
        Integer count = 0;
        String vaccineRegisterId;
        //获取当前用户信息
        LoginUserDTO loginUserDTO = tokenService.getLoginUserDTO(tokenService.getToken(request));
        if (loginUserDTO == null || loginUserDTO.getSysSysuserVo() == null) {
            throw new CustomException("请登录!!!");
        }
        String hospitalCode = loginUserDTO.getSysSysuserVo().getHospitalCode();
        String empNo = loginUserDTO.getSysSysuserVo().getEmpNo();
        String name = loginUserDTO.getSysSysuserVo().getName();

        // 判断是否登记过
        final PatVaccineRegister patVaccineRegister = vaccinationVO.getPatVaccineRegister();
        final QueryWrapper<PatVaccineRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("NAME", patVaccineRegister.getName());
        wrapper.eq("ID_NO", patVaccineRegister.getIdNo());
        final List<PatVaccineRegister> patVaccineRegisters = patVaccineRegisterMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(patVaccineRegisters)) {
            PatVaccineRegister register = patVaccineRegisters.get(0);
            vaccineRegisterId = register.getVaccineRegisterId();
            // if (StringUtils.isNotEmpty(patVaccineRegister.getCardNo())
            //         || !patVaccineRegister.getCardNo().equals(register.getCardNo())) {
            // 暂不做拦截 TODO
            // throw new CustomException("该患者已绑定卡做" + register.getCardNo() + "].");
            // }
            num = patVaccineRegisterMapper.updateById(patVaccineRegister);
        } else {
            patVaccineRegister.setRegisterId(empNo);
            patVaccineRegister.setRegisterName(name);
            vaccineRegisterId = hospitalCode + idUtils.getNextVal(OracleSequenceEnum.SEQ_PAT_VACCINE_REGISTER.getCode()).toString();
            patVaccineRegister.setVaccineRegisterId(vaccineRegisterId);
            patVaccineRegister.setRegisterDate(new Date());
            num = patVaccineRegisterMapper.add(patVaccineRegister);
        }

        // 患者疫苗接种信息
        final PatVaccineInfo patVaccineInfo = vaccinationVO.getPatVaccineInfo();
        if (StringUtils.isNotEmpty(patVaccineInfo.getVaccineCode())) {
            String vaccineInfoId = patVaccineInfo.getVaccineInfoId();
            if (StringUtils.isEmpty(vaccineInfoId)) {
                vaccineInfoId = hospitalCode + idUtils.getNextVal(OracleSequenceEnum.SEQ_PAT_VACCINE_INFO.getCode()).toString();
                patVaccineInfo.setVaccineInfoId(vaccineInfoId);
                patVaccineInfo.setVaccineRegisterId(vaccineRegisterId);
                patVaccineInfo.setRegisterDate(new Date());
                patVaccineInfo.setVaccineDate(new Date());
                patVaccineInfo.setVaccineReaction(Constants.NO);
                infoNum = patVaccineInfoMapper.add(patVaccineInfo);
            } else {
                ValidateUtils.validateEntity(patVaccineInfo, InsertGroup.class);
                infoNum = patVaccineInfoMapper.updateById(patVaccineInfo);
            }
        }
        // 更新接种记录
        List<PatVaccineInfo> patVaccineInfos = vaccinationVO.getPatVaccineInfos();
        if (!CollectionUtils.isEmpty(patVaccineInfos)) {
            for (PatVaccineInfo vaccineInfo : patVaccineInfos) {
                ValidateUtils.validateEntity(vaccineInfo, InsertGroup.class);
            }
            count = vaccinationMapper.batchUpdate(patVaccineInfos);
        }
        return num + infoNum + count;
    }

    @Override
    public BaseResult<Integer> getDosageNum(GetDosageNumVO getDosageNumVO) {
        DosageNumVO dosageNumVO = vaccinationMapper.getDosageNum(getDosageNumVO);
        // 首次登记, 第 1 剂次
        if (dosageNumVO == null) {
            return BaseResult.success(1);
        }
        // 判断与上次疫苗是否同厂家, 不同, 则剂次默认为 1
        final String lastFirmId = dosageNumVO.getFirmId();
        if (!lastFirmId.equals(getDosageNumVO.getFirmId())) {
            return BaseResult.success(1);
        }

        // 判断间隔时间是否足够
        final String[] dayArr = dosageNumVO.getDosageDay().split("-");
        // 上次接种日期
        final Date vaccineDate = dosageNumVO.getVaccineDate();
        // 总剂次数
        final int totalDosageNum = dosageNumVO.getVaccineDosageNum();
        // 本次的剂次数
        final Integer dosageNum = dosageNumVO.getDosageNum() + 1;
        // 超次的情况
        if (dosageNum > totalDosageNum) {
            int days = Integer.parseInt(dayArr[dayArr.length - 1]);
            String msg = "当前疫苗已超过最大剂次数！是否继续？";
            return BaseResult.fail(5, msg, Integer.toString(dosageNum));
        }

        // 间隔天数, 不再校验 TODO
        // 本次应该间隔天数
        // int days = Integer.parseInt(dayArr[dosageNum - 2]);
        // Calendar calendar = Calendar.getInstance();
        // calendar.setTime(vaccineDate);
        // calendar.add(Calendar.DATE, days);
        // final Date date = calendar.getTime();
        // if (date.after(new Date())) {
        //     String message = "计划接种日期为:[" + format.format(date) + "], 时间还不到, 要继续吗?";
        //     return BaseResult.fail(5, message, Integer.toString(dosageNum));
        // }
        return BaseResult.success(dosageNum);
    }

    @Override
    public VaccinationVO query(String name, String idNo) {
        final VaccinationVO vaccinationVO = new VaccinationVO();
        // 查询患者基本信息
        final QueryWrapper<PatVaccineRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        wrapper.eq("ID_NO", idNo);
        wrapper.orderByDesc("REGISTER_DATE");
        List<PatVaccineRegister> patVaccineRegisters = patVaccineRegisterMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(patVaccineRegisters)) {
            return null;
        }
        final PatVaccineRegister patVaccineRegister = patVaccineRegisters.get(0);

        vaccinationVO.setPatVaccineRegister(patVaccineRegister);
        // 查询疫苗信息
        final QueryWrapper<PatVaccineInfo> vaccineWrapper = new QueryWrapper<>();
        vaccineWrapper.eq("VACCINE_REGISTER_ID", patVaccineRegister.getVaccineRegisterId());
        vaccineWrapper.orderByDesc("REGISTER_DATE");
        vaccineWrapper.orderByAsc("VACCINE_CODE");
        final List<PatVaccineInfo> list = patVaccineInfoMapper.selectList(vaccineWrapper);
        vaccinationVO.setPatVaccineInfos(list);
        return vaccinationVO;
    }

    @Override
    public BaseResult<Integer> delete(String vaccineInfoId, Date vaccineDate) {
        if (!DateUtils.isSameDay(vaccineDate, new Date())) {
            throw new CustomException("非今天的接种记录, 不可删除.");
        }
        QueryWrapper<PatVaccineInfo> wrapper = new QueryWrapper<>();
        wrapper.eq(ServiceConstant.VACCINE_INFO_ID, vaccineInfoId);
        return BaseResult.success(patVaccineInfoMapper.delete(wrapper));
    }

    @Override
    public VaccinationCertVO print(VaccinationPrintVO printVO) {
        final VaccinationCertVO vaccinationCertVO = new VaccinationCertVO();
        PatInfoVo patInfoVo = vaccinationMapper.getPatInfo(printVO);
        vaccinationCertVO.setPatInfoVo(patInfoVo);
        List<PatVaccineInfoVO> list = vaccinationMapper.getVaccineInfos(printVO);
        vaccinationCertVO.setPatVaccineInfoVOS(list);
        return vaccinationCertVO;
    }

    @Autowired
    public void setIdUtils(IdUtils idUtils) {
        this.idUtils = idUtils;
    }

    @Autowired
    public void setPatVaccineInfoMapper(PatVaccineInfoMapper patVaccineInfoMapper) {
        this.patVaccineInfoMapper = patVaccineInfoMapper;
    }

    @Autowired
    public void setPatVaccineRegisterMapper(PatVaccineRegisterMapper patVaccineRegisterMapper) {
        this.patVaccineRegisterMapper = patVaccineRegisterMapper;
    }

    @Autowired
    public void setVaccinationMapper(VaccinationMapper vaccinationMapper) {
        this.vaccinationMapper = vaccinationMapper;
    }

    @Autowired
    public void setTokenService(TokenService tokenService) {
        this.tokenService = tokenService;
    }
}
